package com.geezdata.cps.base.utils;

import java.util.List;

import org.apache.commons.math3.distribution.EnumeratedIntegerDistribution;
import org.apache.shiro.util.CollectionUtils;

public class DiscreteDistributionUtil {

	public static final <T> T random(double[] discreteProbabilities, List<T> itemList) {
		if (CollectionUtils.isEmpty(itemList)) {
			return null;
		}
		
		if(discreteProbabilities == null || discreteProbabilities.length <= 0) {
			return null;
		}
    
		int n = discreteProbabilities.length;
		int[] numsToGenerate = new int[n];
		for (int i = 0; i < n; i++) {
			numsToGenerate[i] = i;
        }
		
		EnumeratedIntegerDistribution distribution =
	            new EnumeratedIntegerDistribution(numsToGenerate, discreteProbabilities);

	    int numSamples = 1;
	    int[] samples = distribution.sample(numSamples);
	    int index = samples[0];
	    
	    if (index < 0 || index > itemList.size()) {
	    	return null;
	    }
	    
	    return itemList.get(index);
    }  
	
	public static final <T> T randomWithEqualProbabilities(List<T> itemList) {
		if (CollectionUtils.isEmpty(itemList)) {
			return null;
		}
		
		int n = itemList.size();
		double[] discreteProbabilities = new double[n];
		for (int i = 0; i < n; i++) {
			discreteProbabilities[i] = 1/n;
        }
		
		return random(discreteProbabilities, itemList);
	}
}
